import 'dart:wasm';

import 'package:flutter/material.dart';
import 'package:ml_flutter/pages/mlloginmodel.dart';
import 'package:ml_flutter/pages/mlrequestmodel.dart';
import 'package:ml_flutter/pages/mlwebviewcontroller.dart';
import 'const.dart';
import 'dart:convert';

typedef Block = Future<void> Function();

class MLLoginViewController extends StatefulWidget {
  final Block block;
  MLLoginViewController({Key key, this.block}) : super(key: key);

  @override
  _MLLoginViewControllerState createState() => _MLLoginViewControllerState();
}

class _MLLoginViewControllerState extends State<MLLoginViewController> {
  final TextEditingController _controller =
      TextEditingController.fromValue(TextEditingValue());
  final TextEditingController _passwordcontroller =
      TextEditingController.fromValue(TextEditingValue());
  // 忘记密码
  final String url = MainUrl + '';
  // 帮助
  final String helpUrl =
      MainUrl + '';
  // 用户协议
  final String agreementUrl = MainUrl + '';
  bool _stage = true;


  @override
  Widget build(BuildContext context) => loginView();

// CircularProgressIndicator()


  loginView() => MaterialApp(
      builder: (context, child) => Scaffold(
            resizeToAvoidBottomPadding: false,
            body: GestureDetector(
              onTap: () {
                hideKeyboard();
              },
              child: Stack(
                children: [
                  bodyView(),
                  Align(
                      alignment: Alignment.center,
                      child: Offstage(
                        offstage: _stage,
                        child: CircularProgressIndicator(
                          backgroundColor: Colors.white,
                        ),
                      ))
                ],
              ),
            ),
          ));

  bodyView() {
    return Container(
      child: Column(
        children: <Widget>[
          headView(),
          SizedBox(height: 20),
          inputTextView(),
          SizedBox(height: 40),
          ButtonTheme(
            minWidth: kScreenWidth(context) - 50,
            height: 50,
            child: RaisedButton(
                onPressed: () {
                  loadLoginAction();
                },
                color: Color(int.parse('0xff2692ff')),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(5)),
                ),
                child: Text(
                  '登录',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20.0,
                  ),
                )),
          ),
          webButton(),
          Expanded(
            child: Container(
              padding: EdgeInsets.only(
                bottom: 20 + bottomPadding(context),
              ),
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  GestureDetector(
                    onTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => MLWebViewController(
                                    url: agreementUrl,
                                    title: '用户协议',
                                  )));
                      hideKeyboard();
                    },
                    child: Row(children: <Widget>[
                      Image(
                        image: AssetImage('images/loginSelected.png'),
                        width: 30,
                      ),
                      Text(
                        '阅读并同意',
                        style: TextStyle(color: Colors.black, fontSize: 16.0),
                      )
                    ], mainAxisAlignment: MainAxisAlignment.center),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => MLWebViewController(
                                    url: agreementUrl,
                                    title: '用户协议',
                                  )));
                      hideKeyboard();
                    },
                    child: Text(
                      '《用户协议》',
                      style: TextStyle(color: BlueThemColor, fontSize: 16.0),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
      color: Colors.white,
    );
  }

  Widget headView() => Stack(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(
              top: 0,
              right: 0,
              left: 0,
            ),
            height: 220,
            child: Image(
              image: AssetImage('images/loginImage.png'),
              fit: BoxFit.cover,
            ),
          ),
          Positioned(
            left: kScreenWidth(context) / 2 - 90 / 2,
            top: (220 - 90) / 2,
            child: GestureDetector(
              onTap: () {},
              child: Container(
                alignment: Alignment.center,
                width: 90,
                height: 90,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(45.0),
                  image: DecorationImage(
                    image: AssetImage('images/portrait.png'),
                  ),
                ),
              ),
            ),
          ),
        ],
      );

  Widget inputTextView() => Column(
        children: <Widget>[
          Container(
            child: Column(
              children: <Widget>[
                Container(
                  child: TextField(
                    autofocus: false,
                    obscureText: false,
                    controller: _controller,
                    enableInteractiveSelection: true,
                    style: TextStyle(fontSize: 20.0),
                    cursorColor: Color(int.parse('0xff2692ff')),
                    keyboardType: TextInputType.numberWithOptions(),
                    decoration: InputDecoration(
                      hintText: '账号',
                      contentPadding: EdgeInsets.all(3),
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Color(int.parse('0xff2692ff')),
                        ),
                      ),
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Color(int.parse('0xff2692ff')),
                        ),
                      ),
                      hintStyle: TextStyle(
                          color: Color(int.parse('0xffbbbbbb')),
                          fontSize: 20.0),
                    ),
                  ),
                  height: 60,
                  padding: EdgeInsets.only(
                    left: 20,
                    right: 20,
                  ),
                ),
                Container(
                  child: TextField(
                    autofocus: false,
                    obscureText: true,
                    enableInteractiveSelection: true,
                    style: TextStyle(fontSize: 20.0),
                    cursorColor: Color(int.parse('0xff2692ff')),
                    controller: _passwordcontroller,
                    decoration: InputDecoration(
                      hintText: '密码',
                      contentPadding: EdgeInsets.all(3),
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Color(int.parse('0xff2692ff')),
                        ),
                      ),
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Color(int.parse('0xff2692ff')),
                        ),
                      ),
                      hintStyle: TextStyle(
                          color: Color(int.parse('0xffbbbbbb')),
                          fontSize: 20.0),
                    ),
                  ),
                  height: 60,
                  padding: EdgeInsets.only(
                    left: 20,
                    right: 20,
                  ),
                )
              ],
            ),
          ),
        ],
      );

  void hideKeyboard() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus.unfocus();
    }
  }

  Widget webButton() => Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
              margin: EdgeInsets.only(
                left: 30.0,
                top: 20.0,
              ),
              child: GestureDetector(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => MLWebViewController(
                                url: url,
                                title: '忘记密码',
                              )));
                  hideKeyboard();
                },
                child: Text(
                  '忘记密码',
                  style: TextStyle(
                    color: Color(int.parse('0xff2692ff')),
                    fontSize: 16.0,
                  ),
                ),
              )),
          Container(
              margin: EdgeInsets.only(right: 30.0, top: 20.0),
              child: GestureDetector(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => MLWebViewController(
                                url: helpUrl,
                                title: '帮助',
                              )));
                  hideKeyboard();
                },
                child: Text(
                  '帮助',
                  style: TextStyle(
                    color: Color(int.parse('0xff2692ff')),
                    fontSize: 16.0,
                  ),
                ),
              )),
        ],
      );

  loadLoginAction() {
    // if(_controller.text.length != 11){
    //   showDialogs('请输入账号');
    //   return;
    // }

    //  if(_passwordcontroller.text.length == 0){
    //   showDialogs('请输入密码');
    //   return;
    // }

    String loginUrl = '/sso/app/user/login';
    Map<String, String> dict = {
      // 'loginId': _controller.text,
      // 'password': _passwordcontroller.text,
      'loginId': '15011460001',
      'password': 'cj123456',
      'type': '1',
      'appType': '2',
      'sys': 'zksc',
      'device': 'deviceIsNull%' + _controller.text,
      'appBusType': '1',
      'isNew': 'true',
      'version': '1.0'
    };

    setState(() {
        _stage = false;
    });
    MLReauestModel.shareModel
        .requestUrl(RequestType.POST, loginUrl, dict)
        .then((response) {
      Map<String, dynamic> dic = response;
     setState(() {
        _stage = true;
     });
      if (dic['result'] == 0) {
        MLLoginModel model = MLLoginModel.formJson(dic);
        widget.block();
      } else {
        showDialogs(dic['reason']);
      }
      
    }).catchError((error) {});
  }

// 弹出提示框
  showDialogs(String message) {
    //设置按钮
    Widget okButton = FlatButton(
      child: Text("确定"),
      onPressed: () {
        Navigator.of(context).pop();
      },
    );

    //设置对话框
    AlertDialog alert = AlertDialog(
      title: Text("提示"),
      content: Text(message),
      actions: [
        okButton,
      ],
    );

    //显示对话框
    showDialog(
      context: this.context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
}
